﻿//Role

package  {
	import flash.display.Sprite;
	import flash.events.Event;

	public class Role extends Sprite {
		
		protected var contact:int = 10;
		protected var field:int = 35;
		protected var target:Sprite;
		protected var dir:Number;
		protected var speed:Number;
		protected var vx:Number;
		protected var vy:Number;
		protected var dX:int;
		protected var dY:int;
		
		public var Id:int;
		protected var Side:String;
		public var Opposite:Array;
		protected var Lv:int;
		protected var Hp:int;
		protected var Mp:int;
		
		public function Role() {
			
		}
		
		protected function moveToTarget(e:Event):void {
			if (target) {
				dX = target.x - x;
				dY = target.y - y;
			}
			if (Math.abs(dY) < contact && Math.abs(dX) < contact) {
				vx = vy = 0;
				if (Side == "GOOD") killTarget(target);
				removeEventListener(Event.ENTER_FRAME, moveToTarget);
				addEventListener(Event.ENTER_FRAME, seekTarget);
			}
			else{
				dir = Math.atan2(dY, dX);
				vx = Math.cos(dir) * speed;
				vy = Math.sin(dir) * speed;
				x += vx;
				y += vy;
			}
		}
		
		protected function seekTarget(e:Event):void {
			if (!target) {
				for (var i:int = 0; i < Opposite.length; i++) {
					dX = Opposite[i].x - x;
					dY = Opposite[i].y - y;
					if (Math.abs(dX) < field && Math.abs(dY) < field) {
						Opposite[i].setTarget(this);
						setTarget(Opposite[i]);
					}
				}
			}
			else {
				trace("END SEEKING TARGET");
				removeEventListener(Event.ENTER_FRAME, seekTarget);
				addEventListener(Event.ENTER_FRAME, moveToTarget);
			}
		}
		
		protected function setTarget(t:Sprite):void {
			//TODO: multiple targets to implement...
			target = t;
		}
		
		protected function killTarget(t:Sprite):void {
			if (target == t) {
				target.visible = false;
				target = null;
				removeEventListener(Event.ENTER_FRAME, moveToTarget);
				addEventListener(Event.ENTER_FRAME, seekTarget);
			}
		}
	}
	
}
